package com.info.zhiduoduo.core.service.payment.thirdpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.KltPayConfig;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.PayTestModeConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.pay.TransferPayOrderState;
import com.info.zhiduoduo.common.exception.RollbackException;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.core.dto.transferpay.BaseResDTO;
import com.info.zhiduoduo.core.dto.transferpay.TransferAgentPayFormBean;
import com.info.zhiduoduo.core.dto.transferpay.TransferPayResDTO;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.ZhiduoduoProjectService;

import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TransferPayService implements ThirdPayService {

	@Autowired
	ZhiduoduoProjectService zhiduoduoProjectService;
	@Autowired
	WxMessageService wxMessageService;

	@Autowired
	CommonConfig commonConfig;
	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	PayConfig payConfig;
	@Autowired
	KltPayConfig kltPayConfig;
	@Autowired
	PayTestModeConfig payTestModeConfig;

	@Override
	public SmartResult doCallPayApi(TradeRecord tradeRecord) {
		SmartResult smartResult;
		if (payTestModeConfig.isTestMode()) {
			// 测试
			BaseResDTO<TransferPayResDTO> baseResDTO = new BaseResDTO<>();
			baseResDTO.setResult("success").setCount("1");
			TransferPayResDTO payResultDto = new TransferPayResDTO().setStatus("成功");
			baseResDTO.setData(payResultDto);
			smartResult = SmartResult.success(payResultDto);
		} else {
			//调用第三方支付
			TransferAgentPayFormBean formBean = TransferAgentPayFormBean.of(tradeRecord);
			String url = zddUrlConfig.getBasePayUrl() + payConfig.getTransferAgentPayUrl();
			LogUtil.info("支付调用 url = " + url);
			smartResult = new RestTemplate().postForObject(url, formBean, SmartResult.class);
		}

		return handleTransferPayResult(tradeRecord, smartResult);
	}

	@Override
	public SmartResult handlePayUserTradeState(TradeRecord trade, String orderState, String errorcode, String errormsg) {
		if (trade == null) return SmartResult.success(StatusMsg.StatusMsg_444);
		trade.setErrorcode(errorcode).setErrormsg(errormsg);
		// 失败/成功/已退票
		switch (orderState) {
			case TransferPayOrderState.HANDLING:
				trade.setTradestate(Constants.TRADE_IN_PROCESS);
				break;
			case TransferPayOrderState.SUCCESS:
				trade.setTradestate(Constants.TRADE_SUCCESS).setFinishtime(new Date());
				zhiduoduoProjectService.doAfterPayUserTradeSucceed(trade);
				break;
			case TransferPayOrderState.FAIL:
			case TransferPayOrderState.REFUND:
				trade.setTradestate(Constants.TRADE_FAIL).setFinishtime(new Date());
				wxMessageService.notifyAdminPaymentFail(trade);
				break;
			case "":
			default:
				trade.setTradestate(Constants.TRADE_FAIL).setFinishtime(new Date());
				wxMessageService.notifyAdminPaymentFail(trade);
				break;
		}

		if (trade.updateById()) return SmartResult.success();
		return SmartResult.fail(StatusMsg.StatusMsg_445);
	}

	@Override
	public SmartResult handlePayJiugeTradeState(TradeRecord trade, String orderState, String errorcode, String errormsg) {
		return SmartResult.fail(StatusMsg.StatusMsg_445);
	}

	private SmartResult handleTransferPayResult(TradeRecord trade, SmartResult smartResult) {
		if (smartResult.getObject() == null || smartResult.isFailed()) {
			//支付失败,回滚并显示失败原因
			String rollbackMsg = "";
			if (smartResult.getObject() != null) {
				BaseResDTO<TransferPayResDTO> payResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
						new TypeReference<BaseResDTO<TransferPayResDTO>>() {
						});
				rollbackMsg = payResult.getMsg();
			} else {
				rollbackMsg = smartResult.getMsg();
			}

			LogUtil.info("支付失败,回滚并显示失败原因");
			throw new RollbackException(rollbackMsg);

		} else {
			//支付接口调用成功,查看交易结果
			BaseResDTO<TransferPayResDTO> payResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
					new TypeReference<BaseResDTO<TransferPayResDTO>>() {
					});
			TransferPayResDTO resData = payResult.getData();
			if ("success".equals(payResult.getResult()) && resData != null) {
				trade.setPartnerOrderNo(resData.getBusinessrecordnumber()).setRequestid(resData.getBusinessnumber());
				return handlePayUserTradeState(trade, resData.getStatus(), payResult.getCode(), payResult.getMsg());
			} else {
				return handlePayUserTradeState(trade, "", payResult.getCode(), payResult.getMsg());
			}

		}
	}
}
